package com.wholesale;


import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.beans.LoginRequest;
import com.wholesale.beans.LoginResponse;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;

public class UserRegisterLayout extends LinearLayout implements OnClickListener {   
	private ViewFlipper viewFlipper ;
	private Context context ;
	private View baseView ;
	private Button leftButton ;
	private Button rightButton ;
	private TextView headView ;
	
	private TextView userNameView ;
	private TextView passwordView ;
	private TextView confirmPasswordView ;
	private String userName,password,confirmpass;
	private RegisterTask loginTask ;
	//  构造函数  
	public UserRegisterLayout(Context context,final ViewFlipper viewFlipper){
		super(context);
		this.viewFlipper = viewFlipper ;
		this.context = context ;
		//加载需要的属性，加载方法一的子Layout  
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.userregist, this);  
		leftButton = (Button)baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Back");
		leftButton.setOnClickListener(this);
		rightButton = (Button)baseView.findViewById(R.id.rightBtn);
		rightButton.setText("Register");
		rightButton.setOnClickListener(this);
		headView = (TextView)baseView.findViewById(R.id.title);
		headView.setText("Register");
		
		userNameView = (TextView) findViewById(R.id.username_text);
		passwordView = (TextView) findViewById(R.id.userpassword_text);
		confirmPasswordView = (TextView) findViewById(R.id.confirmPassword_text);
	}
	
	public void dialog(String title, String message,String button) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton(button, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
	class RegisterTask extends AsyncTask<LoginRequest, Integer, LoginResponse>{
		private Context context ;
		ProgressDialog pdialog;
		public RegisterTask(Context context){
			this.context = context ;
			pdialog = new ProgressDialog(context);
			pdialog.setTitle("Registering...");
			pdialog.setMessage("Please wait...");
			pdialog.setCancelable(true);
			pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
					dialog.cancel();
					loginTask.cancel(true);
				}
			});
			pdialog.show();
		}
		@Override
		protected LoginResponse doInBackground(LoginRequest... params) {
			LoginResponse loginResponse = new LoginResponse();
			String result = WebServiceClient.registerNewUser(params[0].getUserId(), params[0].getPassword());
			if(result.equals("1")){ // userName&Email is existed
				loginResponse.setReturnType(-1);
			}else if(result.equals("2")){
				loginResponse.setReturnType(-2);
			}else{
				loginResponse = WebServiceClient.login(params[0].toJsonString());
				if(loginResponse.getReturnType()==0){
					Constants.loginResponse = loginResponse ;
					Constants.userInfo = WebServiceClient.getUserInfo(loginResponse.getUserId(), loginResponse.getUserToken());
				}
			}
			return  loginResponse;
		}
		@Override
		protected void onPostExecute(LoginResponse result) {
			pdialog.dismiss();
			if(result.getReturnType() == 1){
				dialog("Error","invilid password!","Confirm");
			}else if(result.getReturnType() == 2){
				dialog("Error","userId not exist!","Confirm");
			}else if(result.getReturnType() == 3){
				dialog("Error","Server error!","Confirm");
			}else if(result.getReturnType() == -1){
				dialog("Error","userName&Email is existed","Confirm");
			}else if(result.getReturnType() == -2){
				dialog("Error","Server error!","Confirm");
			}else{
				viewFlipper.removeView(UserRegisterLayout.this);
				int size = viewFlipper.getChildCount();
				viewFlipper.showPrevious();
				viewFlipper.removeViewAt(size-1);
			}
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
		
	}
	
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager)((Activity) getContext()).getSystemService(Context.INPUT_METHOD_SERVICE);  

		switch (v.getId()) {
		case R.id.leftBtn:
			if (imm.isActive()){
				imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); 
			}
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		case R.id.rightBtn:
			
			if (imm.isActive()){
				imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); 
			}
			
			userName = userNameView.getText().toString().trim();
			password = passwordView.getText().toString().trim();
			confirmpass = confirmPasswordView.getText().toString();
			
			String pattern = "\\w{3,20}@\\w+\\.(com|org|cn|org|net|gov)";
			boolean b = Pattern.matches(pattern,userName);
			if(!b){
				dialog("Sorry","Username should be email!","OK");
				return;
			}
			
			String message = null;
		
			if ("".equals(password)) {
					message ="Password should be 6-12!";
					dialog("Sorry",message,"OK");
					return;
				}
			if(password.length()<6){
				message ="Password should be 6-12!";
				dialog("Sorry",message,"OK");
				return;
			}
			if ("".equals(confirmpass)) {
				message ="Please enter the confirm password!";
				dialog("Sorry",message,"OK");
				return;
			}
			
			if(!password.equals(confirmpass)){
				dialog("Sorry","Inconsistent with the password twice!","OK");
				return;
			}else{
				LoginRequest login = new LoginRequest();
				login.setPassword(password);
				login.setUserId(userName);
				loginTask = new RegisterTask(context);
				loginTask.execute(login);
			}
			
			break;
		default:
			break;
		}
	}
}
